package logic

import (
	"MyBlogv2/blog-common/Enum"
	"MyBlogv2/blog-common/HttpCode"
	"MyBlogv2/blog-common/define"
	helper "MyBlogv2/blog-common/helper"
	"MyBlogv2/blog-common/models"
	"context"
	"github.com/jinzhu/copier"
	"time"

	"MyBlogv2/Servers/UserAction/internal/svc"
	"MyBlogv2/Servers/UserAction/userAction"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *UserAction.UserRegisterDto) (*UserAction.CommonResponse, error) {
	user := in

	code, err := models.RDb.Get(context.Background(), user.Email).Result()
	if err != nil {
		return &UserAction.CommonResponse{
			Code: int64(HttpCode.VERIFY_CODE_ERROR),
		}, nil
	}
	if user.Code != code {
		return &UserAction.CommonResponse{
			Code: int64(HttpCode.VERIFY_CODE_ERROR),
		}, nil
	}
	user.Password, _ = helper.GetBcryptPassword(user.Password)
	var userRegister models.User
	copier.Copy(&userRegister, &user)
	userRegister.RegisterIp = in.RegisterIp
	userRegister.RegisterType = Enum.GetType(Enum.EMAIL)
	userRegister.Gender = define.DEFAULT_GENDER
	userRegister.Avatar = define.DEFAULT_AVATAR
	userRegister.Intro = define.DEFAULT_INTRODUCTION
	userRegister.Nickname = user.Username
	userRegister.LoginTime = models.MyTime(time.Now())
	userRegister.IsDisAble = define.DEFAULT_STATUS
	userRegister.IsDeleted = define.DEFAULT_STATUS
	models.RDb.Del(context.Background(), user.Email)
	err = models.Db.Create(&userRegister).Error
	var userRole models.UserRole
	userRole.RoleId = define.DEFAULT_ROLE
	userRole.UserId = userRegister.Id
	models.Db.Model(new(models.UserRole)).Create(&userRole)
	if err != nil {
		return &UserAction.CommonResponse{
			Code: int64(HttpCode.FAILURE),
		}, nil
	}
	return &UserAction.CommonResponse{
		Code: int64(HttpCode.SUCCESS),
	}, nil

}
